package com.stars.easyms.datasource.mybatis;

import com.stars.easyms.datasource.mybatis.transaction.EasyMsSpringManagedTransactionFactory;
import com.stars.easyms.datasource.util.XmlMapperParseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.type.TypeHandler;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.NestedIOException;
import org.springframework.core.io.Resource;
import org.springframework.util.ReflectionUtils;

import javax.sql.DataSource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import static org.springframework.util.ObjectUtils.isEmpty;
import static org.springframework.util.StringUtils.hasLength;
import static org.springframework.util.StringUtils.tokenizeToStringArray;

/**
 * <p>className: EasyMsSqlSessionFactoryBean</p>
 * <p>description: EasyMs的SqlSessionFactoryBean定制化类</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-07-10 11:07
 */
@Slf4j
public final class EasyMsSqlSessionFactoryBean extends SqlSessionFactoryBean {

    private Configuration configuration;

    private DataSource dataSource;

    private TransactionFactory transactionFactory;

    private String environmentName = EasyMsSqlSessionFactoryBean.class.getSimpleName();

    private Resource[] mapperLocations;

    private String typeAliasesPackage;

    private Class<?> typeAliasesSuperType;

    private Interceptor[] plugins;

    private TypeHandler<?>[] typeHandlers;

    private String typeHandlersPackage;

    private Class<?>[] typeAliases;

    private ObjectFactory objectFactory;

    private ObjectWrapperFactory objectWrapperFactory;

    private DatabaseIdProvider databaseIdProvider;

    public EasyMsSqlSessionFactoryBean(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        super.setDataSource(dataSource);
    }

    @Override
    public void setTransactionFactory(TransactionFactory transactionFactory) {
        this.transactionFactory = transactionFactory;
        super.setTransactionFactory(transactionFactory);
    }

    @Override
    public void setMapperLocations(Resource[] mapperLocations) {
        List<Resource> resourceList = new ArrayList<>();
        for (Resource resource : mapperLocations) {
            if (XmlMapperParseUtil.isMybatisMapperXml(resource)) {
                resourceList.add(resource);
            }
        }
        Resource[] resources = resourceList.toArray(new Resource[0]);
        this.mapperLocations = resources;
        super.setMapperLocations(resources);
    }

    @Override
    public void setTypeAliasesPackage(String typeAliasesPackage) {
        this.typeAliasesPackage = typeAliasesPackage;
        super.setTypeAliasesPackage(typeAliasesPackage);
    }

    @Override
    public void setTypeAliasesSuperType(Class<?> typeAliasesSuperType) {
        this.typeAliasesSuperType = typeAliasesSuperType;
        super.setTypeAliasesSuperType(typeAliasesSuperType);
    }

    @Override
    public void setPlugins(Interceptor[] plugins) {
        this.plugins = plugins;
        super.setPlugins(plugins);
    }

    @Override
    public void setTypeHandlersPackage(String typeHandlersPackage) {
        this.typeHandlersPackage = typeHandlersPackage;
        super.setTypeHandlersPackage(typeHandlersPackage);
    }

    @Override
    public void setTypeHandlers(TypeHandler<?>[] typeHandlers) {
        this.typeHandlers = typeHandlers;
        super.setTypeHandlers(typeHandlers);
    }

    @Override
    public void setTypeAliases(Class<?>[] typeAliases) {
        this.typeAliases = typeAliases;
        super.setTypeAliases(typeAliases);
    }

    @Override
    public void setObjectFactory(ObjectFactory objectFactory) {
        this.objectFactory = objectFactory;
        super.setObjectFactory(objectFactory);
    }

    @Override
    public void setObjectWrapperFactory(ObjectWrapperFactory objectWrapperFactory) {
        this.objectWrapperFactory = objectWrapperFactory;
        super.setObjectWrapperFactory(objectWrapperFactory);
    }

    @Override
    public void setDatabaseIdProvider(DatabaseIdProvider databaseIdProvider) {
        this.databaseIdProvider = databaseIdProvider;
        super.setDatabaseIdProvider(databaseIdProvider);
    }

    @Override
    protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
        if (this.transactionFactory == null) {
            this.transactionFactory = new EasyMsSpringManagedTransactionFactory();
        }
        Method setConfigurationMethod = ReflectionUtils.findMethod(SqlSessionFactoryBean.class, "setConfiguration", Configuration.class);
        if (setConfigurationMethod != null) {
            try {
                setConfigurationMethod.invoke(this, configuration);
                super.setTransactionFactory(this.transactionFactory);
                return super.buildSqlSessionFactory();
            } catch (IllegalAccessException | InvocationTargetException e) {
                log.error("Class 'SqlSessionFactoryBean' Method 'setConfiguration' invoke failure!");
            }
        }
        if (this.objectFactory != null) {
            configuration.setObjectFactory(this.objectFactory);
        }
        if (this.objectWrapperFactory != null) {
            configuration.setObjectWrapperFactory(this.objectWrapperFactory);
        }
        if (hasLength(this.typeAliasesPackage)) {
            String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage,
                    ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
            for (String packageToScan : typeAliasPackageArray) {
                configuration.getTypeAliasRegistry().registerAliases(packageToScan,
                        typeAliasesSuperType == null ? Object.class : typeAliasesSuperType);
                if (log.isDebugEnabled()) {
                    log.debug("Scanned package: '{}' for aliases", packageToScan);
                }
            }
        }
        if (!isEmpty(this.typeAliases)) {
            for (Class<?> typeAlias : this.typeAliases) {
                configuration.getTypeAliasRegistry().registerAlias(typeAlias);
                if (log.isDebugEnabled()) {
                    log.debug("Registered type alias: '{}'", typeAlias);
                }
            }
        }
        if (!isEmpty(this.plugins)) {
            for (Interceptor plugin : this.plugins) {
                configuration.addInterceptor(plugin);
                if (log.isDebugEnabled()) {
                    log.debug("Registered plugin: '{}'", plugin);
                }
            }
        }
        if (hasLength(this.typeHandlersPackage)) {
            String[] typeHandlersPackageArray = tokenizeToStringArray(this.typeHandlersPackage,
                    ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
            for (String packageToScan : typeHandlersPackageArray) {
                configuration.getTypeHandlerRegistry().register(packageToScan);
                if (log.isDebugEnabled()) {
                    log.debug("Scanned package: '{}' for type handlers", packageToScan);
                }
            }
        }
        if (!isEmpty(this.typeHandlers)) {
            for (TypeHandler<?> typeHandler : this.typeHandlers) {
                configuration.getTypeHandlerRegistry().register(typeHandler);
                if (log.isDebugEnabled()) {
                    log.debug("Registered type handler: '{}'", typeHandler);
                }
            }
        }
        Environment environment = new Environment(this.environmentName, this.transactionFactory, this.dataSource);
        configuration.setEnvironment(environment);
        if (this.databaseIdProvider != null) {
            try {
                configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
            } catch (SQLException e) {
                throw new NestedIOException("Failed getting a databaseId", e);
            }
        }
        if (!isEmpty(this.mapperLocations)) {
            for (Resource mapperLocation : this.mapperLocations) {
                if (mapperLocation == null) {
                    continue;
                }
                try {
                    XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
                            configuration, mapperLocation.toString(), configuration.getSqlFragments());
                    xmlMapperBuilder.parse();
                } catch (Exception e) {
                    throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
                } finally {
                    ErrorContext.instance().reset();
                }

                if (log.isDebugEnabled()) {
                    log.debug("Parsed mapper file: '{}'", mapperLocation);
                }
            }
        } else if (log.isDebugEnabled()) {
            log.debug("Property 'mapperLocations' was not specified or no matching resources found");
        }
        return new DefaultSqlSessionFactory(configuration);
    }
}